let max_rewards = 40;
const pause_time = 9000;
let search_words = [];
let currentSearchCount = 0;
let isSearching = false;

// 扩展默认搜索词列表，包含更多样化的内容
const default_search_words = [
    // 古诗词
    "盛年不重来，一日难再晨", "千里之行，始于足下", "少年易学老难成，一寸光阴不可轻",
    "山重水复疑无路，柳暗花明又一村", "海内存知己，天涯若比邻", "落红不是无情物，化作春泥更护花",
    // 现代文学
    "时间是最好的老师", "知识改变命运", "梦想照进现实", "青春无悔", "奋斗的青春最美丽",
    // 科技话题
    "人工智能发展", "科技创新", "数字化转型", "5G技术", "云计算应用", "大数据分析",
    // 生活话题
    "健康生活方式", "环保理念", "可持续发展", "教育重要性", "文化传承", "社会进步",
    // 时事热点
    "经济发展", "社会和谐", "科技进步", "文化交流", "国际合作", "和平发展"
];
// 更新热搜获取方式 - 只从rebang.today获取
const hot_search_sources = [
    {
        name: 'RebangToday',
        url: 'https://rebang.today/',
        type: 'webpage'
    }
];
let current_source_index = 0;

const CHECK_INTERVAL = 60 * 60 * 1000;  // 检查间隔（1小时）
const TARGET_PC_POINTS = 90;  // 目标电脑搜索积分
let lastSearchDate = null;  // 记录最后搜索日期

let searchLock = false;
let searchLockTimeout = null;

let rewardsLock = false;
let rewardsLockTimeout = null;

let searchProgress = {
    currentCount: 0,
    maxRewards: 40,
    searchWords: [],
    date: null
};

let autoCheckInterval = null;

function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}

function AutoStrTrans(st) {
    let yStr = st;
    let rStr = "";
    let zStr = "";
    let prePo = 0;
    for (let i = 0; i < yStr.length;) {
        let step = parseInt(Math.random() * 5) + 1;
        if (i > 0) {
            zStr = zStr + yStr.substr(prePo, i - prePo) + rStr;
            prePo = i;
        }
        i = i + step;
    }
    if (prePo < yStr.length) {
        zStr = zStr + yStr.substr(prePo, yStr.length - prePo);
    }
    return zStr;
}

async function getSearchWords() {
    const today = new Date().toDateString();
    const stored = await chrome.storage.local.get(['searchedWords', 'searchProgress']);
    let searchedWords = stored.searchedWords || {};

    // 清理非当天的搜索记录
    if (searchedWords.date !== today) {
        searchedWords = {
            date: today,
            words: []
        };
        await chrome.storage.local.set({ searchedWords });
    }

    try {
        // 尝试从rebang.today获取热搜词
        for (const source of hot_search_sources) {
            try {
                console.log(`尝试从 ${source.name} 获取热搜词...`);
                
                // 使用Chrome扩展的content script功能来获取动态内容
                const words = await getHotSearchFromRebang();
                
                if (words && words.length > 0) {
                    // 过滤已搜索的词
                    const validWords = words.filter(word => 
                        word && 
                        word.length > 1 && 
                        !searchedWords.words.includes(word) &&
                        word.trim().length > 0
                    );
                    
                    if (validWords.length > 0) {
                        console.log(`成功从 ${source.name} 获取到 ${validWords.length} 个有效搜索词`);
                        console.log('获取到的搜索词示例:', validWords.slice(0, 5));
                        return validWords.slice(0, 20); // 限制返回数量
                    }
                }
                
                console.log(`从 ${source.name} 未获取到有效搜索词`);
                
            } catch (error) {
                console.error(`从 ${source.name} 获取搜索词失败:`, error);
            }
        }
    } catch (error) {
        console.error('获取搜索词过程出错:', error);
    }

    console.log('所有外部源均失败，使用智能默认搜索词');
    
    // 使用智能默认词库，包含更多样化的内容
    const extendedDefaultWords = [
        ...default_search_words,
        // 科技热点
        "科技创新", "人工智能", "5G技术", "云计算", "大数据", "物联网", "区块链",
        "新能源汽车", "绿色能源", "环保技术", "可持续发展", "数字化转型",
        "在线教育", "远程办公", "数字支付", "电商发展", "直播带货",
        // 生活健康
        "健康生活", "运动健身", "心理健康", "营养饮食", "医疗健康",
        "文化传承", "艺术创作", "音乐欣赏", "电影娱乐", "旅游出行",
        // 经济社会
        "经济发展", "金融市场", "投资理财", "创业创新", "就业机会",
        "社会和谐", "公平正义", "法治建设", "民主参与", "民生改善",
        "国际合作", "一带一路", "全球治理", "文化交流", "和平发展",
        // 添加更多随机化内容
        "今日新闻", "热点事件", "社会关注", "民生话题", "科技前沿",
        "教育改革", "医疗发展", "环保行动", "文化创新", "体育赛事",
        "美食文化", "时尚潮流", "旅游景点", "历史传承", "未来展望"
    ];
    
    // 添加随机化功能，每天生成不同的词序
    const currentDate = new Date().toDateString();
    const seed = currentDate.split('').reduce((a, b) => a + b.charCodeAt(0), 0);
    
    // 使用种子随机化数组
    const shuffledWords = [...extendedDefaultWords];
    for (let i = shuffledWords.length - 1; i > 0; i--) {
        const j = (seed + i) % (i + 1);
        [shuffledWords[i], shuffledWords[j]] = [shuffledWords[j], shuffledWords[i]];
    }
    
    const availableWords = shuffledWords.filter(word => !searchedWords.words.includes(word));
    
    if (availableWords.length === 0) {
        console.log('所有默认搜索词已用完，重置搜索词列表');
        searchedWords.words = [];
        await chrome.storage.local.set({ searchedWords });
        return shuffledWords.slice(0, 20);
    }

    return availableWords.slice(0, 20);
}


// 新增：从rebang.today获取热搜词的函数
async function getHotSearchFromRebang() {
    try {
        console.log('开始从rebang.today获取热搜词...');
        
        // 创建一个新标签页来访问rebang.today
        const tab = await new Promise((resolve, reject) => {
            chrome.tabs.create({
                url: 'https://rebang.today/',
                active: false
            }, (tab) => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve(tab);
                }
            });
        });
        
        console.log('标签页创建成功，等待页面加载...');
        
        // 等待页面加载完成
        await new Promise(resolve => setTimeout(resolve, 5000));
        
        // 在页面中执行脚本获取热搜词
        const results = await chrome.scripting.executeScript({
            target: { tabId: tab.id },
            func: () => {
                console.log('在rebang.today页面中执行脚本...');
                
                // 等待页面完全加载
                return new Promise((resolve) => {
                    const checkForContent = () => {
                        let words = [];
                        
                        try {
                            // 根据实际网页结构，尝试获取热搜词
                            // 1. 获取文章标题（主要热搜内容）
                            const articleTitles = document.querySelectorAll('h1, h2, h3, h4, h5, h6, [class*="title"], [class*="headline"]');
                            articleTitles.forEach(el => {
                                const text = el.textContent?.trim();
                                if (text && text.length > 3 && text.length < 100) {
                                    // 过滤掉导航和无关文本
                                    if (!text.match(/^(首页|更多|查看|点击|搜索|热门|排行|榜单|登录|注册|设置|帮助|订阅|综合|科技|娱乐|社区|财经|开发)$/) &&
                                        text.match(/[\u4e00-\u9fa5]/)) { // 包含中文字符
                                        words.push(text);
                                    }
                                }
                            });
                            
                            // 2. 获取链接文本
                            const links = document.querySelectorAll('a');
                            links.forEach(link => {
                                const text = link.textContent?.trim();
                                if (text && text.length > 3 && text.length < 100) {
                                    if (!text.match(/^(首页|更多|查看|点击|搜索|热门|排行|榜单|登录|注册|设置|帮助|订阅|综合|科技|娱乐|社区|财经|开发|换一换)$/) &&
                                        text.match(/[\u4e00-\u9fa5]/)) {
                                        words.push(text);
                                    }
                                }
                            });
                            
                            // 3. 获取列表项文本
                            const listItems = document.querySelectorAll('li, [class*="item"], [class*="list"]');
                            listItems.forEach(item => {
                                const text = item.textContent?.trim();
                                if (text && text.length > 3 && text.length < 100) {
                                    if (!text.match(/^(首页|更多|查看|点击|搜索|热门|排行|榜单|登录|注册|设置|帮助|订阅|综合|科技|娱乐|社区|财经|开发|换一换)$/) &&
                                        text.match(/[\u4e00-\u9fa5]/)) {
                                        words.push(text);
                                    }
                                }
                            });
                            
                            // 4. 获取所有包含中文的文本节点
                            const allElements = document.querySelectorAll('*');
                            allElements.forEach(el => {
                                const text = el.textContent?.trim();
                                if (text && text.length > 3 && text.length < 100) {
                                    // 检查是否是热搜相关的内容
                                    if (text.match(/[\u4e00-\u9fa5]/) && 
                                        !text.match(/^(首页|更多|查看|点击|搜索|热门|排行|榜单|登录|注册|设置|帮助|订阅|综合|科技|娱乐|社区|财经|开发|换一换|热度|来源|知乎|微博|IT之家|虎扑|腾讯新闻)$/) &&
                                        !text.match(/^\d+$/) &&
                                        !text.match(/^[a-zA-Z\s]+$/)) {
                                        words.push(text);
                                    }
                                }
                            });
                            
                        } catch (e) {
                            console.log('获取内容时出错:', e);
                        }
                        
                        // 去重并过滤
                        const uniqueWords = [...new Set(words)]
                            .filter(word => word && word.trim().length > 3)
                            .filter(word => !word.match(/^(热度|来源|知乎|微博|IT之家|虎扑|腾讯新闻|全站|今日|本周|本月|全部节点)$/))
                            .filter(word => word.match(/[\u4e00-\u9fa5]/)) // 必须包含中文字符
                            .slice(0, 30); // 限制数量
                        
                        console.log(`找到 ${uniqueWords.length} 个热搜词:`, uniqueWords.slice(0, 10));
                        resolve(uniqueWords);
                    };
                    
                    // 等待页面加载完成
                    setTimeout(checkForContent, 5000);
                });
            }
        });
        
        // 关闭标签页
        await chrome.tabs.remove(tab.id);
        
        if (results && results[0] && results[0].result) {
            console.log('成功从rebang.today获取热搜词:', results[0].result);
            return results[0].result;
        } else {
            console.log('未能从rebang.today获取到热搜词');
            return [];
        }
        
    } catch (error) {
        console.error('从rebang.today获取热搜词失败:', error);
        return [];
    }
}

async function performSearch() {
    if (!isSearching || currentSearchCount >= max_rewards) {
        isSearching = false;
        searchLock = false;
        if (searchLockTimeout) {
            clearTimeout(searchLockTimeout);
            searchLockTimeout = null;
        }
        await chrome.storage.local.set({
            isSearching: false,
            searchProgress: null
        });
        return;
    }

    // 添加错误重试机制
    try {
        const randomDelay = Math.floor(Math.random() * 20000) + 10000;
        const randomString = generateRandomString(4);
        const randomCvid = generateRandomString(32);

        let nowtxt = search_words[currentSearchCount];
        if (!nowtxt) {
            console.error('搜索词获取失败，重新获取搜索词');
            search_words = await getSearchWords();
            nowtxt = search_words[currentSearchCount];
            if (!nowtxt) {
                throw new Error('无法获取有效的搜索词');
            }
        }

        // 记录已搜索的词
        const stored = await chrome.storage.local.get('searchedWords');
        let searchedWords = stored.searchedWords || {
            date: new Date().toDateString(),
            words: []
        };
        if (!searchedWords.words.includes(nowtxt)) {
            searchedWords.words.push(nowtxt);
            await chrome.storage.local.set({ searchedWords });
        }

        nowtxt = AutoStrTrans(nowtxt);

        const searchUrl = `https://${currentSearchCount <= max_rewards / 2 ? 'www' : 'cn'}.bing.com/search?q=${encodeURI(nowtxt)}&form=${randomString}&cvid=${randomCvid}`;

        // 使用 Promise 包装 tab 操作
        await new Promise((resolve, reject) => {
            chrome.tabs.create({ url: searchUrl, active: false }, async (tab) => {
                try {
                    await new Promise(resolve => setTimeout(resolve, 5000));
                    await chrome.tabs.remove(tab.id);

                    currentSearchCount++;
                    searchProgress = {
                        currentCount: currentSearchCount,
                        maxRewards: max_rewards,
                        searchWords: search_words,
                        date: new Date().toDateString()
                    };
                    await chrome.storage.local.set({
                        currentCount: currentSearchCount,
                        searchProgress
                    });

                    if (currentSearchCount % 5 === 0) {
                        await new Promise(resolve => setTimeout(resolve, pause_time));
                    }

                    resolve();
                } catch (error) {
                    reject(error);
                }
            });
        });

        // 确保继续执行下一次搜索，即使popup关闭
        if (isSearching && currentSearchCount < max_rewards) {
            // 使用chrome.alarms来替代setTimeout
            const alarmName = 'nextSearch';
            chrome.alarms.create(alarmName, {
                when: Date.now() + randomDelay
            });
        }
    } catch (error) {
        console.error('搜索过程出错:', error);
        if (isSearching) {
            console.log('3秒后重试搜索...');
            // 使用chrome.alarms来替代setTimeout
            chrome.alarms.create('retrySearch', {
                when: Date.now() + 3000
            });
        }
        searchLock = false;
        if (searchLockTimeout) {
            clearTimeout(searchLockTimeout);
            searchLockTimeout = null;
        }
    }
}

// 添加alarm监听器
chrome.alarms.onAlarm.addListener((alarm) => {
    if (alarm.name === 'nextSearch' || alarm.name === 'retrySearch') {
        performSearch();
    }
});

async function saveRewardsInfo(rewardsInfo) {
    const dataToSave = {
        ...rewardsInfo,
        lastUpdateTime: new Date().getTime()
    };
    await chrome.storage.local.set({ rewardsInfo: dataToSave });
    return dataToSave;
}

async function getRewardsInfo(forceUpdate = false) {
    if (rewardsLock) {
        console.log('已有获积分任务在进行中，跳过本次请求');
        const stored = await chrome.storage.local.get('rewardsInfo');
        return stored.rewardsInfo || {
            success: false,
            error: '正在获取积分中',
            totalPoints: '获取中',
            dailyPoints: '获取中',
            pcSearchPoints: '获取中'
        };
    }

    try {
        rewardsLock = true;
        rewardsLockTimeout = setTimeout(() => {
            rewardsLock = false;
            rewardsLockTimeout = null;
        }, 5 * 60 * 1000);

        if (!forceUpdate) {
            const stored = await chrome.storage.local.get('rewardsInfo');
            if (stored.rewardsInfo) {
                const lastUpdateTime = stored.rewardsInfo.lastUpdateTime;
                const currentTime = new Date().getTime();
                if (currentTime - lastUpdateTime < 5 * 60 * 1000) {
                    rewardsLock = false;
                    clearTimeout(rewardsLockTimeout);
                    return stored.rewardsInfo;
                }
            }
        }

        console.log('开始获取积分信息...');

        const tab = await new Promise((resolve, reject) => {
            try {
                chrome.tabs.create(
                    {
                        url: 'https://rewards.bing.com/pointsbreakdown',
                        active: false
                    },
                    (tab) => {
                        if (chrome.runtime.lastError) {
                            reject(chrome.runtime.lastError);
                        } else {
                            resolve(tab);
                        }
                    }
                );
            } catch (e) {
                reject(e);
            }
        });

        console.log('标签页创建成功，ID:', tab.id);
        console.log('等待页面加载...');
        await new Promise(resolve => setTimeout(resolve, 5000));

        console.log('开始执行脚本...');
        const results = await chrome.scripting.executeScript({
            target: { tabId: tab.id },
            func: () => {
                console.log('在页面中执行脚本...');

                const totalPointsElement = document.querySelector('#balanceToolTipDiv > p > mee-rewards-counter-animation > span');
                const dailyPointsElement = document.querySelector('#dailypointToolTipDiv > p > mee-rewards-counter-animation > span');
                const pcSearchPointsElement = document.querySelector('#userPointsBreakdown > div > div:nth-child(2) > div > div:nth-child(1) > div > div.pointsDetail > mee-rewards-user-points-details > div > div > div > div > p.pointsDetail.c-subheading-3.ng-binding > b');
                const levelElement = document.querySelector('#meeGradientBanner > div > div > div > p');

                console.log('找到的元素:', {
                    totalPointsElement: totalPointsElement?.outerHTML,
                    dailyPointsElement: dailyPointsElement?.outerHTML,
                    pcSearchPointsElement: pcSearchPointsElement?.outerHTML,
                    levelElement: levelElement?.outerHTML
                });

                const totalPoints = totalPointsElement?.textContent?.trim() || '获取失败';
                const dailyPoints = dailyPointsElement?.textContent?.trim() || '获取失败';
                const pcSearchPoints = pcSearchPointsElement?.textContent?.trim() || '获取失败';

                const levelText = levelElement?.textContent?.trim() || '';
                const levelMatch = levelText.match(/\d+/);
                const level = levelMatch ? levelMatch[0] : '?';

                return {
                    success: true,
                    totalPoints,
                    dailyPoints,
                    pcSearchPoints,
                    level,
                    debug: {
                        url: window.location.href,
                        title: document.title
                    }
                };
            }
        });

        console.log('脚本执行结果:', results);
        await chrome.tabs.remove(tab.id);
        console.log('标签页已关闭');

        if (!results || !results[0] || !results[0].result) {
            throw new Error('未获取到执行结果');
        }

        rewardsLock = false;
        clearTimeout(rewardsLockTimeout);

        return await saveRewardsInfo(results[0].result);

    } catch (error) {
        rewardsLock = false;
        if (rewardsLockTimeout) {
            clearTimeout(rewardsLockTimeout);
            rewardsLockTimeout = null;
        }

        console.error('获取积分信息失败，详细错误:', error);
        const errorResult = {
            success: false,
            error: error.message,
            totalPoints: '获取失败',
            dailyPoints: '获取失败',
            pcSearchPoints: '获取失败',
            debug: {
                errorType: error.constructor.name,
                errorMessage: error.message,
                errorStack: error.stack
            }
        };
        await saveRewardsInfo(errorResult);
        return errorResult;
    }
}

async function resetDailyCount() {
    const today = new Date().toDateString();
    if (lastSearchDate !== today) {
        console.log('重置搜索状态...');
        lastSearchDate = today;
        currentSearchCount = 0;
        isSearching = false;
        current_source_index = 0;

        await chrome.storage.local.set({
            lastSearchDate: today,
            currentCount: 0,
            isSearching: false,
            searchProgress: null,
            searchedWords: {
                date: today,
                words: []
            }
        });

        console.log('搜索状态已重置');
    }
}

function getLevelTargetPoints() {
    return userLevel > 1 ? 90 : 60;  // 2级及以上目标90分，1级标60分
}

async function checkAndSearch() {
    const today = new Date().toDateString();

    if (searchLock) {
        console.log('已有搜索任务在进行中，跳过本次检查');
        return;
    }

    try {
        searchLock = true;
        console.log('开始检查积分状态...');

        // 检查日期并重置
        if (lastSearchDate !== today) {
            console.log('日期已更新，重置搜索状态');
            await resetDailyCount();
            await getRewardsInfo(true);
        }

        // 获取最新状态
        const stored = await chrome.storage.local.get(['isSearching', 'searchProgress']);
        console.log('当前存储的搜索状态:', stored);

        const rewardsInfo = await getRewardsInfo(true);
        userLevel = parseInt(rewardsInfo.level) || 1;
        const targetPoints = getLevelTargetPoints();
        const pcPoints = parseInt(rewardsInfo.pcSearchPoints) || 0;

        console.log('当前电脑搜索积分:', pcPoints);
        console.log('用户等级:', userLevel, '目标积分:', targetPoints);

        // 只根据积分判断是否需要继续搜索
        if (pcPoints >= targetPoints) {
            console.log(`当前PC搜索积分(${pcPoints})已达到等级${userLevel}的目标积分(${targetPoints})`);
            isSearching = false;
            await chrome.storage.local.set({ isSearching: false });
            searchLock = false;
            return;
        }

        // 计算还需要搜索多少次
        const estimatedSearchesNeeded = Math.ceil((targetPoints - pcPoints) / 3); // 假设每次搜索获得3分
        const neededSearches = Math.min(estimatedSearchesNeeded, max_rewards);

        console.log(`当前积分: ${pcPoints}, 目标积分: ${targetPoints}, 预计还需搜索: ${estimatedSearchesNeeded}次`);

        if (neededSearches > 0) {
            isSearching = true;
            if (!stored.searchProgress || stored.searchProgress.date !== today) {
                currentSearchCount = 0;
                max_rewards = neededSearches;
                const words = await getSearchWords();
                search_words = words;
            }

            await chrome.storage.local.set({
                isSearching: true,
                currentCount: currentSearchCount,
                searchProgress: {
                    currentCount: currentSearchCount,
                    maxRewards: max_rewards,
                    searchWords: search_words,
                    date: today
                }
            });

            performSearch();
        } else {
            searchLock = false;
        }
    } catch (error) {
        console.error('检查积分时出错:', error);
        searchLock = false;
        if (searchLockTimeout) {
            clearTimeout(searchLockTimeout);
            searchLockTimeout = null;
        }
        setTimeout(() => {
            checkAndSearch().catch(err => {
                console.error('重试检查积分时出错:', err);
            });
        }, 3000);
    }
}

chrome.storage.local.get(['lastSearchDate', 'dailySearchCount', 'searchProgress'], async (result) => {
    const today = new Date().toDateString();
    if (result.lastSearchDate !== today) {
        await resetDailyCount();
    } else {
        lastSearchDate = result.lastSearchDate;
        dailySearchCount = result.dailySearchCount || 0;

        if (result.searchProgress && result.searchProgress.date === today) {
            searchProgress = result.searchProgress;
            currentSearchCount = searchProgress.currentCount;
            max_rewards = searchProgress.maxRewards;
            search_words = searchProgress.searchWords;
        }
    }
});

function startAutoCheck() {
    if (!autoCheckInterval) {
        checkAndSearch(); // 立即执行一次
        autoCheckInterval = setInterval(checkAndSearch, CHECK_INTERVAL);

        // 更新扩展图标状态
        updateExtensionIcon(true);
    }
}

function stopAutoCheck() {
    if (autoCheckInterval) {
        clearInterval(autoCheckInterval);
        autoCheckInterval = null;

        // 更新扩展图标状态
        updateExtensionIcon(false);
    }
}

// 添加更新扩展图标的函数
function updateExtensionIcon(isSearching) {
    if (!isSearching) {
        // 如果不在搜索,使用黑白图标
        chrome.action.setIcon({
            path: {
                "16": "images/rewards_none16.png",
                "48": "images/rewards_none48.png",
                "128": "images/rewards_none128.png"
            }
        });
        return;
    }

    // 如果在搜索,使用彩色图标
    chrome.action.setIcon({
        path: {
            "16": "images/rewards16.png",
            "48": "images/rewards48.png",
            "128": "images/rewards128.png"
        }
    });
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "startSearch") {
        if (searchLock) {
            sendResponse({
                status: "rejected",
                reason: "已有搜索任务在进行中"
            });
            return true;
        }

        startAutoCheck(); // 启动自动检查
        resetDailyCount();
        const maxSearches = getMaxDailySearches();

        getRewardsInfo(true).then(rewardsInfo => {
            userLevel = parseInt(rewardsInfo.level) || 1;
            const targetPoints = getLevelTargetPoints();
            const pcPoints = parseInt(rewardsInfo.pcSearchPoints) || 0;

            if (pcPoints >= targetPoints) {
                sendResponse({
                    status: "rejected",
                    reason: `当前已达到${userLevel}级用户的每日电脑搜索积分上限(${targetPoints}分)`
                });
                return;
            }

            if (!isSearching && dailySearchCount < maxSearches) {
                isSearching = true;
                currentSearchCount = 0;
                const searchLimit = Math.min(maxSearches - dailySearchCount, max_rewards);
                max_rewards = searchLimit;

                Promise.all([
                    chrome.storage.local.set({ isSearching: true, currentCount: 0 }),
                    getSearchWords()
                ]).then(([_, words]) => {
                    search_words = words;
                    performSearch();
                    sendResponse({
                        status: "started",
                        buttonState: {
                            startEnabled: false,
                            stopEnabled: true
                        }
                    });
                }).catch(error => {
                    isSearching = false;
                    sendResponse({
                        status: "rejected",
                        reason: "启动搜索失败: " + error.message,
                        buttonState: {
                            startEnabled: true,
                            stopEnabled: false
                        }
                    });
                });
            } else {
                sendResponse({
                    status: "rejected",
                    reason: dailySearchCount >= maxSearches ?
                        `已达到${userLevel}级用户每日搜索次数上限(${maxSearches}次)` : "搜索正在进行中",
                    buttonState: {
                        startEnabled: !isSearching,
                        stopEnabled: isSearching
                    }
                });
            }
        }).catch(error => {
            sendResponse({
                status: "rejected",
                reason: "检查积分失败: " + error.message,
                buttonState: {
                    startEnabled: true,
                    stopEnabled: false
                }
            });
        });

        return true;
    }

    else if (request.action === "stopSearch") {
        stopAutoCheck(); // 停止自动检查
        isSearching = false;
        searchLock = false;
        if (searchLockTimeout) {
            clearTimeout(searchLockTimeout);
            searchLockTimeout = null;
        }
        chrome.storage.local.set({
            isSearching: false,
            searchProgress: null  // 清除搜索进度
        })
            .then(() => sendResponse({
                status: "stopped",
                buttonState: {
                    startEnabled: true,
                    stopEnabled: false
                }
            }))
            .catch(error => sendResponse({
                status: "error",
                reason: "停止搜索失败: " + error.message,
                buttonState: {
                    startEnabled: false,
                    stopEnabled: true
                }
            }));
        return true;
    }

    else if (request.action === "getStatus") {
        sendResponse({
            isSearching: isSearching,
            currentCount: currentSearchCount,
            maxCount: max_rewards,
            currentKeyword: isSearching && currentSearchCount < search_words.length ?
                search_words[currentSearchCount] : '',
            buttonState: {
                startEnabled: !isSearching,
                stopEnabled: isSearching
            }
        });
        return true;
    }

    else if (request.action === "getRewardsInfo") {
        getRewardsInfo(request.forceUpdate)
            .then(response => {
                sendResponse({
                    ...response,
                    buttonState: {
                        startEnabled: !isSearching,
                        stopEnabled: isSearching
                    }
                });
            })
            .catch(error => {
                sendResponse({
                    success: false,
                    error: error.message,
                    totalPoints: '获取失败',
                    dailyPoints: '获取失败',
                    pcSearchPoints: '获取失败',
                    lastUpdateTime: new Date().getTime(),
                    debug: {
                        errorType: error.constructor.name,
                        errorMessage: error.message,
                        errorStack: error.stack
                    },
                    buttonState: {
                        startEnabled: !isSearching,
                        stopEnabled: isSearching
                    }
                });
            });
        return true;
    }

    else if (request.action === "getSearchWords") {
        sendResponse({
            searchWords: search_words,
            currentCount: currentSearchCount,
            date: searchProgress.date
        });
        return true;
    }

    return false;
});

// 在扩展启动时自动开始检查
chrome.runtime.onStartup.addListener(startAutoCheck);
chrome.runtime.onInstalled.addListener(startAutoCheck);

// 添加定期保存和恢复搜索状态的功能
chrome.storage.local.get(['isSearching'], (result) => {
    if (result.isSearching) {
        startAutoCheck();
    }
}); 